//
//  MyViewController.m
//  Tour
//
//  Created by 张张烨 on 16/3/7.
//  Copyright © 2016年 张中烨. All rights reserved.
//

#import "MyViewController.h"
#import "rigthItem/RigthViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <Foundation/NSDictionary.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <MessageUI/MessageUI.h>
#import "AppDelegate.h"

@interface MyViewController ()<UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, MFMailComposeViewControllerDelegate>
@property (nonatomic, strong) BaseTableView *tableview;
@property (nonatomic, strong) UIImageView *backImageview;
@property (nonatomic, strong) UIImageView *userImageView;
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureStillImageOutput *imageOutput;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewSubLayer;
//@property (nonatomic, strong) UIView *preview;/**< 预览图片 */
@property (nonatomic, assign) CGFloat cache;
@property(nonatomic,strong)UIView *backView;

@end

@implementation MyViewController

- (void)viewWillAppear:(BOOL)animated
{
    NSString *userImg = [[NSUserDefaults standardUserDefaults]objectForKey:@"userImg"];
    if (userImg) {
        
        //将字符串转化Data
        NSData *userimg = [[NSData alloc] initWithBase64EncodedString:userImg options:NSDataBase64DecodingIgnoreUnknownCharacters];
        [self.userImageView setImage:[UIImage imageWithData:userimg]];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的";
//    [self rightItem]; /**< 右侧按钮,将来有可能删除掉, 里面创建个table,可以添加些竞拍到的上线没用的功能  */
    [self createSubviews];
    [self networkingConnect];
    
    /**<  夜间没事 */
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    self.backView  = [[ UIView alloc] initWithFrame:CGRectMake(0, 0, KUAN *375, GAO *667)];
    self.backView.backgroundColor = [UIColor blackColor];
    self.backView.alpha = 0.5;
    self.backView.userInteractionEnabled = NO;
    [delegate.window addSubview:_backView];
    _backView.hidden = YES;
    _backView.hidden = YES;
}

/**<  右侧按钮 */
- (void)rightItem
{
    UIBarButtonItem *rigthItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"369"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:(UIBarButtonItemStylePlain) target:self action:@selector(setUp)];
    self.navigationItem.rightBarButtonItem = rigthItem;
    
}

- (void)createSubviews
{
    //tableview
    self.tableview = [[BaseTableView alloc] initWithFrame:FRAME style:UITableViewStylePlain];
    [self.view addSubview:_tableview];
    _tableview.delegate = self;
    _tableview.dataSource = self;
     _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableview registerClass:[BaseTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    //上方视图
    self.backImageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 4)];
    _backImageview.contentMode = UIViewContentModeScaleAspectFill;
    _backImageview.clipsToBounds = YES;
    _backImageview.userInteractionEnabled = YES;
    _backImageview.image = [UIImage imageNamed:@"backimg.jpg"];
    [self.view addSubview:_backImageview];
    
    self.userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 5, SCREEN_WIDTH / 5)];
    _userImageView.center = CGPointMake(_backImageview.center.x, _backImageview.center.y);
    _userImageView.contentMode = UIViewContentModeScaleAspectFill;
    _userImageView.layer.cornerRadius = _userImageView.frame.size.width / 2;
    _userImageView.clipsToBounds = YES;
    _userImageView.userInteractionEnabled = YES;
    _userImageView.image = [UIImage imageNamed:@"touxiang.jpg"];
    [self.backImageview addSubview:_userImageView];
    
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeImgAction)];
    [self.userImageView addGestureRecognizer:tap];
    
    _tableview.tableHeaderView = _backImageview;
}

//网络连接
- (void)networkingConnect
{
    //session连接到captureDevive
    [self setSession:[[AVCaptureSession alloc] init]];
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
    if ([self.session canAddInput:deviceInput])
        [self.session addInput:deviceInput];
    
    [self setImageOutput:[[AVCaptureStillImageOutput alloc] init]];
    NSDictionary *setting = [[NSDictionary alloc]initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
    [self.imageOutput setOutputSettings:setting];
    [self.session addOutput:self.imageOutput];
    [self.session startRunning];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSArray *array = @[@"我的收藏",@"夜间模式",@"清除缓存",@"意见反馈",@"特别声明"];
    for (NSInteger i = 0; i < 5; i++) {
        if (indexPath.row == i) {
            cell.textLabel.text = array[i];
        }
    }
    if (indexPath.row == 1) {
        
        //创建switch
        UISwitch *nightSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH*0.8, cell.contentView.bounds.size.height * 0.15, SCREEN_WIDTH * 0.15, cell.contentView.bounds.size.height * 0.6)];
        
        
        [nightSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        [cell addSubview:nightSwitch];
    }
    
    [cell NightWithType:UIViewColorTypeNormal];
    return cell;
}

#pragma mark - 选择按钮的动作方法
- (void)switchAction:(UISwitch *)switchBtn{
    if (switchBtn.on) {
        self.backView.hidden = NO;
    }else
    {
        self.backView.hidden = YES;
    }
//         [ThemeManage shareThemeManage].isNight = ![ThemeManage shareThemeManage].isNight;
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeColor" object:nil];
//        [[NSUserDefaults standardUserDefaults] setBool:[ThemeManage shareThemeManage].isNight forKey:@"night"];

}


//点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中
    if (indexPath.row == 0) {
        ShouCangViewController *shouCang = [[ShouCangViewController alloc] init];
        [self.navigationController pushViewController:shouCang animated:YES];
    }
    
    if (indexPath.row == 2) {
        //计算缓存
        //创建管理器对象
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //获取沙河路径
        NSString *catch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        if ([fileManager fileExistsAtPath:catch]) {
            NSArray *files = [fileManager subpathsAtPath:catch];
            //遍历所有文件
            for (NSInteger i = 0; i < files.count; i++) {
                NSString *filePath = [catch stringByAppendingPathComponent:files[i]];
                //获取文件大小
                float k = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
                self.cache =  self.cache + k;
                NSLog(@"%2lf", self.cache);
            }
        }
        NSString *messageStr = [NSString stringWithFormat:@"是否确认清除%.2lfM内存?", self.cache / 1024 / 1024];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:messageStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        //        [alertView dismissWithClickedButtonIndex:0 animated:YES];
    }else if (indexPath.row == 4)
    {
        SpecialDeclareVC *specialVC = [[SpecialDeclareVC alloc] init];
        [self.navigationController pushViewController:specialVC animated:YES];
    }else if (indexPath.row == 3)
    {
        [self sendMailInApp];
    }
}

//弹窗协议方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //清除缓存
    //cache文件夹里面的缓存
    if (buttonIndex == 1) {
        dispatch_async(
                       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                       , ^{
                           NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                           
                           NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                           NSLog(@"files :%lu",(unsigned long)[files count]);
                           for (NSString *p in files) {
                               NSError *error;
                               NSString *path = [cachPath stringByAppendingPathComponent:p];
                               if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                   [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                               }
                           }
                           [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];
                           
                       });
        
        // 将缓存数值置为0
        self.cache = 0;
        //清除离线缓存
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"detail-1-1"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"detail-1-2"];
        
    }
}

-(void)clearCacheSuccess
{
    NSLog(@"清理成功");
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:nil message:@"清除成功!" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}

// 激活邮件功能
- (void)sendMailInApp
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass) {
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:nil message:@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        return;
    }
    if (![mailClass canSendMail]) {
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:nil message:@"用户没有设置邮件账户" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        return;
    }
    [self displayMailPicker];
}

//调出邮件发送窗口
- (void)displayMailPicker
{
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
    mailPicker.mailComposeDelegate = self;
    [mailPicker setTitle:@"内容"];
    
    //设置主题
    [mailPicker setSubject: @"意见反馈"];
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject: @"939495554@qq.com"];
    [mailPicker setToRecipients: toRecipients];
    //添加抄送
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"275400625@163.com", @"third@example.com", nil];
    [mailPicker setCcRecipients:ccRecipients];
    //添加密送
    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
    [mailPicker setBccRecipients:bccRecipients];
    
    //    // 添加一张图片
    //    UIImage *addPic = [UIImage imageNamed: @"Icon@2x.png"];
    //    NSData *imageData = UIImagePNGRepresentation(addPic);            // png
    //    //关于mimeType：http://www.iana.org/assignments/media-types/index.html
    //    [mailPicker addAttachmentData: imageData mimeType: @"" fileName: @"Icon.png"];
    
    //添加一个pdf附件
    //    NSString *file = [self fullBundlePathFromRelativePath:@"高质量C++编程指南.pdf"];
    //    NSData *pdf = [NSData dataWithContentsOfFile:file];
    //    [mailPicker addAttachmentData: pdf mimeType: @"" fileName: @"高质量C++编程指南.pdf"];
    
    NSString *emailBody = @"<font color='red'>eMail</font> 正文";
    [mailPicker setMessageBody:emailBody isHTML:YES];
    [self presentViewController:mailPicker animated:YES completion:^{
        
    }];
}


#pragma mark - 实现 MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    //关闭邮件发送窗口
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    NSString *msg;
    switch (result) {
        case MFMailComposeResultCancelled:
            msg = @"用户取消编辑邮件";
            break;
        case MFMailComposeResultSaved:
            msg = @"用户成功保存邮件";
            break;
        case MFMailComposeResultSent:
            msg = @"用户点击发送，将邮件放到队列中，还没发送";
            break;
        case MFMailComposeResultFailed:
            msg = @"用户试图保存或者发送邮件失败";
            break;
        default:
            break;
    }
    NSLog(@"%@", msg);
}

- (void)setUp
{
    RigthViewController *next = [[RigthViewController alloc] init];
    [self.navigationController pushViewController:next animated:YES];
}
//更换头像
- (void)changeImgAction
{
    // 下方弹出选择框
    UIActionSheet *actinSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册选择", nil];
    [actinSheet showInView:self.view];
}

// UIActionSheet点击协议方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }else if (buttonIndex == actionSheet.destructiveButtonIndex) {
        [self camera];
    }else {
        [self library];
    }
    
}

- (void)library
{
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypeSavedPhotosAlbum])
    {
        UIImagePickerController *imagePicker =
        [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType =
        UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.mediaTypes = [NSArray arrayWithObjects:
                                  (NSString *) kUTTypeImage,
                                  nil];
        imagePicker.allowsEditing = NO;
        [self presentViewController:imagePicker animated:YES completion:^(void){}];
    }
}

// 调用照相机的方法
- (void)camera
{
    //判断是否可以打开相机，模拟器此功能无法使用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:^{
            
        }];

    }else{
        //如果没有提示用户
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"Drat!" otherButtonTitles:nil];
        [alert show];
    }
}


//图片选中照片后
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    [picker dismissViewControllerAnimated:YES completion:^(void){}];
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info
                          objectForKey:UIImagePickerControllerOriginalImage];
        
        [self presentEditViewController:image];
    }
}

- (void)presentEditViewController:(UIImage*) uiimage {
    UIImage *newImage = [FilterVC effectImage:uiimage byFilterName:@"None"];
    
    FilterVC *viewController = [[FilterVC alloc] init];

    [viewController setOriginalImage:uiimage];
    [viewController setImage:newImage];

    [self.navigationController pushViewController:viewController animated:YES];
    NSLog(@"push");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
